<template>
  <div>
    <van-popup
      :show="show"
      position="bottom"
      @close="onClose"
    >
      <van-picker :columns="columns" @change="jumpQ" />
    </van-popup>
    <van-dialog id="van-dialog" />
    <div style="height: 100rpx">
      <div class="exam_top" v-if="!finished">
        <div class="emam_exit"><van-button plain type="primary" @click="backToList">退出</van-button></div>
        <div class="emam_time" @click="onShow"></div>
        <div class="exam_submit"><van-button plain type="danger" @click="submit">提交</van-button></div>
      </div>
    </div>
    <div class="test_type">【单选题】</div>
    <div>
      <div class="test_content">{{index + 1}}、{{test.myQuestions[index].content}}（{{test.myQuestions[index].choice}}）</div>
      <div class="choices">
        <van-radio-group :value="radio" @change="onChange" :disabled="finished">
          <van-radio v-for="(item, i) in test.myQuestions[index].answer"
                     :key="i"
                     checked-color="#07c160" :name="test.myQuestions[index].answer[i]">{{litter[i]}}. {{test.myQuestions[index].answer[i]}}</van-radio>
        </van-radio-group>
      </div>

      <div v-if="!finished"></div>
      <div v-else>{{repreat}}</div>
    </div>
    <div class="b_button">
      <div class="distance"><van-button plain type="primary" @click="toLast">上一题</van-button></div>
      <div class="distance"><van-button plain type="primary" @click="toDetail">题目</van-button></div>
      <div class="distance"><van-button plain type="primary" @click="toNext">下一题</van-button></div>
    </div>
  </div>
</template>

<script>
  import Dialog from '@/../static/vant/dialog/dialog'
  import { mapState } from 'vuex'
  import GetAnswerApi from '@/api/getAnswer'

  export default {
    name: 'Exam',
    data () {
      return {
        timer: '',
        repreat: '',
        finished: false,
        show: false,
        countDownNum: '',
        countTime: '00:00:00',
        index: 0,
        eindex: 0,
        radio: '',
        test: {},
        columns: [],
        litter: ['A', 'B', 'C', 'D', 'E', 'F']
      }
    },
    computed: {
      ...mapState(['examList', 'openId'])
    },
    mounted () {
      console.log(this.test)
      this.countDownNum = this.test.countTime
      this.radio = this.test.myQuestions[this.index].choice
      if (this.test.usingTime === 0) {
        this.onShow()
      } else {
        this.finished = true
      }
      var i = 0
      while (i < this.test.myQuestions.length) {
        this.columns[i] = Math.floor([i]) + 1
        i++
      }
      // console.log('index = ' + this.index)
      this.isRight(this.index)
    },
    beforeMount () {
      console.log(this.$mp.query)
      this.initialize()
      // 根据list返回的参数向服务端请求考试
      // this.test = return()
    },
    methods: {
      initialize () {
        this.index = 0
        this.countTime = '00:00:00'
        this.finished = false
        this.show = false
        if (this.$mp.query.eindex != null) {
          this.eindex = parseInt(this.$mp.query.eindex, 10)
          this.test = this.examList[this.eindex]
          this.test.userId = this.openId
        }
        // console.log(this.eindex)
        if (this.$mp.query.index != null) {
          this.index = parseInt(this.$mp.query.index, 10)
        }
      },
      backToList () {
        Dialog.confirm({
          title: '是否确认退出联系',
          message: '确认后则取消，成绩无效'
        }).then(() => {
          // 连接后台
          // 消除试题缓存
          this.timer = clearInterval(this.timer)
          wx.switchTab({url: '../band/main'})
        }).catch(() => {
          // on cancel
        })
      },
      jumpQ (event) {
        this.index = event.mp.detail.value - 1
        this.isRight(this.index)
        this.radio = this.test.myQuestions[this.index].choice
        this.onClose()
      },
      onClose () {
        this.show = false
      },
      onChange (event) {
        // console.log(event)
        // this.radio = event.mp.detail
        this.test.myQuestions[this.index].choice = event.mp.detail
        this.radio = this.test.myQuestions[this.index].choice
        // console.log(this.test.myQuestions[this.index].choice)
      },
      chackAnswer () {
        var i = 0
        var score = 0
        this.disabled = true
        for (;i < this.test.myQuestions.length; i++) {
          if (this.test.myQuestions[i].choice === this.test.myQuestions[i].ranswer) {
            // console.log('进入对答案')
            // console.log(this.test.myQuestions[i].choice)
            // console.log(this.test.myQuestions[i].ranswer)
            this.test.myQuestions[i].isCorrect = true
            score = score + 1
            // this.isRight(i)
          }
        }
        score = score * 100 / this.test.myQuestions.length
        score = parseInt(score, 10)
        this.$store.dispatch('getScore', score)
      },
      isRight (index) {
        console.log(this.test.myQuestions[index].isCorrect)
        console.log(this.test.myQuestions[index].ranswer)
        if (this.test.myQuestions[index].isCorrect) {
          this.radio = this.test.myQuestions[index].choice
          this.repreat = '答案正确'
        } else {
          this.repreat = '正确答案为：' + this.test.myQuestions[index].ranswer
        }
      },
      submit (e) {
        Dialog.confirm({
          title: '是否确认提交',
          message: '确认后则提交答案，获得练习成绩'
        }).then(() => {
          // 连接后台
          this.timer = clearInterval(this.timer)
          // 暂时是错的，目前usingTime为剩余时间
          this.test.usingTime = this.countDownNum
          GetAnswerApi.getAnswer(this.test)
            .then((resp) => {
              this.test = resp
              console.log('成功传送')
              // 往服务端获取答案
              this.chackAnswer()
              this.test.usingTime = 1000
              this.$store.dispatch('getExam', this.test)
              console.log(this.test)
              wx.redirectTo({url: '../practiseresult/main'})
            })
            .catch((error) => {
              console.log(error)
            })
        }).catch(() => {
          // on cancel
        })
      },
      toNext () {
        if (this.index + 1 < this.test.myQuestions.length) {
          this.index++
          this.isRight(this.index)
          this.radio = this.test.myQuestions[this.index].choice
        }
      },
      toLast () {
        if (this.index > 0) {
          this.index--
          this.isRight(this.index)
          this.radio = this.test.myQuestions[this.index].choice
        }
      },
      toDetail () {
        // 显示全部题目序号
        this.show = true
      },
      onShow () {
        // this.countDown()
        // 取消计时
      },
      countDown () {
        let that = this
        let countDownNum = that.countDownNum// 获取倒计时初始值
        // 如果将定时器设置在外面，那么用户就看不到countDownNum的数值动态变化，所以要把定时器存进data里面
        that.timer = setInterval(function () { // 这里把setInterval赋值给变量名为timer的变量
          var h = '00'
          var m = '00'
          var s = '00'
          // 每隔一秒countDownNum就减一，实现同步
          h = Math.floor(countDownNum / 3600)
          m = Math.floor(countDownNum / 60 % 60)
          s = Math.floor(countDownNum % 60)
          s = s > 9 ? s : `0${s}`
          m = m > 9 ? m : `0${m}`
          h = h > 9 ? h : `0${h}`
          countDownNum--
          // eslint-disable-next-line eqeqeq
          // 然后把countDownNum存进data，好让用户知道时间在倒计着
          that.countDownNum = countDownNum
          // 在倒计时还未到0时，这中间可以做其他的事情，按项目需求来
          that.countTime = h + ':' + m + ':' + s
          // eslint-disable-next-line eqeqeq
          if (countDownNum == 0) {
            // 这里特别要注意，计时器是始终一直在走的，如果你的时间为0，那么就要关掉定时器！不然相当耗性能
            // 因为timer是存在data里面的，所以在关掉时，也要在data里取出后再关闭
            that.timer = clearInterval(that.timer)
            // 关闭定时器之后，可作其他处理codes go here
          }
        }, 1000)
      }
    }
  }
</script>

<style scoped>
  .exam_top{
    display: flex;
    flex-direction: row;
    justify-content: center;
  }
  .emam_time{
    font-size: 30px;
    margin-left: 250rpx;
    margin-right: 250rpx;
    flex-direction: column;
    justify-content: center;
  }
  .test_content{
    height: 500rpx;
    margin-bottom: 100rpx;
  }
  .test_type{
    font-size:  20px;
  }
  .choices{
    padding: 20rpx;
  }
  .b_button{
    display: flex;
    position:fixed;
    bottom:0;
  }
  .distance{
    margin: 50rpx;
  }
</style>
